import pandas as pd
import numpy as np
from app.model.model import SourcePath
from config import config_database
import os


class ServiceSourcePath(object):
    def __init__(self):
        super(ServiceSourcePath, self).__init__()

    def list_source_path(self):
        res = list()
        data = None
        try:
            data = np.array(pd.read_csv(
                config_database['file_source_path'])).tolist()
            for item in data:
                res.append(SourcePath(item[0], item[1]).toJson())
            return {"errcode": 200, "errmsg": "ok", "data": res}
        except:
            return {"errcode": 400, "errmsg": "读取{filename}文件失败".format(filename=config_database['file_source_path'])}

    def update_source_path(self, **args):
        data = SourcePath(1, args['path'])
        inList = list()
        inList.append(data.toList())
        try:
            pd.DataFrame(inList).to_csv(
                config_database['file_source_path'], index=False, header=['id', 'path']
            )
            return {"errcode": 200, "errmsg": "ok"}
        except:
            return {"errcode": 400, "errmsg": "写入{filename}文件失败".format(filename=config_database['file_source_path'])}

    def list_source_package(self):
        path = np.array(pd.read_csv(
            config_database['file_source_path']))[0][1]
        print(path)
        try:
            data = os.listdir(path)
            return {"errcode": 200, "errmsg": "ok", "data": data}
        except:
            return {"errcode": 200, "errmsg": "路径错误，导致读取文件夹失败", "data": []}
